<template>
  <view class="question-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误提示 -->
    <view v-else-if="error" class="error-container">
      <text class="error-text">错误: {{ error }}</text>
      <button class="retry-btn" @click="loadQuestions">重试</button>
    </view>

    <!-- 问题内容 (仅在加载完成且无错误时显示) -->
    <view v-else>
      <!-- 进度条 -->
      <view class="progress-bar">
        <text class="prev-btn" @click="navigateBack"> 上一题</text>
        <view class="progress">
          <view class="progress-fill" :style="{ width: progress + '%' }"></view>
        </view>
        <text class="progress-text">{{ progress }}%</text>
      </view>

      <!-- 问题内容 -->
      <view class="question-content">
        <text class="question-title">{{ currentQuestion.title }}</text>
        <view class="options">
          <view class="option-item" :class="{ 'selected': option.isSelect === 1 }"
            v-for="(option, index) in currentQuestion.children" :key="index" @click="handleOptionSelect(option)">
            <text class="option-text">{{ option.answer }}</text>
          </view>
        </view>
      </view>

      <!-- 底部按钮 -->
      <view class="bottom-buttons">
        <button class="next-btn" :disabled="!canProceed" @click="navigateToNext" style="line-height:2.55555556;">
          {{ isLastQuestion ? '查看结果' : '下一题' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    questionApi
  } from '@/api/questionApi';
  export default {
    data() {
      return {
        questions: [],
        currentQuestionIndex: 0,
        userAnswers: [],
        loading: true,
        error: null
      };
    },
    created() {
      this.loadQuestions();
    },
    computed: {
      currentQuestion() {
        return this.questions[this.currentQuestionIndex];
      },
      progress() {
        return Math.round(((this.currentQuestionIndex + 1) / this.questions.length) * 100);
      },
      isLastQuestion() {
        return this.currentQuestionIndex === this.questions.length - 1;
      },
      canProceed() {
        // 检查是否至少选择了一个选项
        return this.currentQuestion.children.some(option => option.isSelect === 1);
      }
    },
    methods: {
      handleOptionSelect(option) {
        if (this.currentQuestion.problemType === "SINGLE") {
          // 单选：取消其他选项
          this.currentQuestion.children.forEach(item => {
            item.isSelect = item === option ? 1 : 0;
          });
        } else {
          // 多选：切换当前选项
          option.isSelect = option.isSelect === 1 ? 0 : 1;
          // 处理"以上均无"的逻辑
          const allNoneOption = this.currentQuestion.children.find(item => item.answer === "以上均无");
          if (allNoneOption && option === allNoneOption) {
            this.currentQuestion.children.forEach(item => {
              item.isSelect = item === allNoneOption ? 1 : 0;
            });
          } else if (allNoneOption && allNoneOption.isSelect === 1) {
            allNoneOption.isSelect = 0;
          }
        }
      },
      navigateToNext() {
        // 保存当前答案
        this.saveAnswer();
        if (this.isLastQuestion) {
          // 提交答案到后端
          this.submitAnswers();
        } else {
          // 下一题
          this.currentQuestionIndex++;
        }
      },
      navigateBack() {
        if (this.currentQuestionIndex > 0) {
          this.currentQuestionIndex--;
        } else {
          uni.navigateBack();
        }
      },
      // 提交答案到后端API
      submitAnswers() {
        // 打印选择的答案数据
        console.log('用户选择的答案数据:', this.userAnswers);

        // 调用API提交答案
        questionApi.postTimu(this.userAnswers)
          .then(res => {
            // 提交成功，跳转到结果页并带上返回数据

            console.log('提交答案后')
            console.log(res)

            uni.showToast({
              title: '提交完成',
              duration: 2000
            });

            console.log(encodeURIComponent(JSON.stringify(res.data)));
            uni.navigateTo({
              url: `/pages/question/result?data=${encodeURIComponent(JSON.stringify(res.data))}`
            });

          }).catch(err => {
            uni.showToast({
              title: `提交失败: ${err.message}`,
              icon: 'none'
            });
          });
      },
      async loadQuestions() {
        try {
          this.loading = true;
          const data = await questionApi.getQuestions();
          console.log(data);
          this.questions = data;
        } catch (err) {
          this.error = err.message;
          uni.showToast({
            title: '加载问题失败',
            icon: 'none'
          });
        } finally {
          this.loading = false;
        }
      },
      saveAnswer() {
        // 获取选中的选项（包含完整信息）
        const selectedOptions = this.currentQuestion.children
          .filter(option => option.isSelect === 1)
          .map(option => ({
            alias: option.alias,
            answer: option.answer,
            isSelect: option.isSelect
          }));

        // 查找已有答案索引
        const existingIndex = this.userAnswers.findIndex(ans => ans.id === this.currentQuestion.id.toString());
        if (existingIndex > -1) {
          this.userAnswers.splice(existingIndex, 1);
        }

        // 按要求格式化答案数据
        const formattedAnswer = {
          id: this.currentQuestion.id.toString(),
          userAnswer: this.currentQuestion.problemType === 'SINGLE' ? selectedOptions[0] : selectedOptions
        };
        this.userAnswers.push(formattedAnswer);
      }
    }
  };
</script>

<style scoped>
  .question-container {
    padding: 20rpx;
    min-height: 100vh;
    background-color: #ffffff;
  }

  .progress-bar {
    display: flex;
    align-items: center;
    margin-bottom: 60rpx;
    padding: 0 10rpx;
  }

  .prev-btn {
    font-size: 28rpx;
    color: #333333;
    margin-right: 20rpx;
  }

  .progress {
    flex: 1;
    height: 12rpx;
    background-color: #f0f0f0;
    border-radius: 6rpx;
    overflow: hidden;
  }

  .progress-fill {
    height: 100%;
    background-color: #FFD700;
    transition: width 0.3s ease;
  }

  .progress-text {
    font-size: 28rpx;
    color: #333333;
    margin-left: 20rpx;
  }

  .question-title {
    font-size: 36rpx;
    color: #333333;
    margin-bottom: 40rpx;
    text-align: center;
  }

  .options {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .option-item {
    padding: 30rpx;
    border: 2rpx solid #e5e5e5;
    border-radius: 16rpx;
    font-size: 30rpx;
    color: #333333;
    transition: all 0.2s ease;
  }

  .option-item.selected {
    background-color: #FFD700;
    border-color: #FFD700;
    color: #333333;
  }

  .bottom-buttons {
    position: fixed;
    bottom: 40rpx;
    left: 0;
    right: 0;
    padding: 0 40rpx;
  }

  .next-btn {
    width: 100%;
    height: 90rpx;
    background-color: #000000;
    color: #ffffff;
    font-size: 32rpx;
    border-radius: 0rpx;
    border: none;
  }

  .next-btn:disabled {
    background-color: #cccccc;
  }
</style>